#include <stdio.h>
#include <curl/curl.h>
#include <openssl/md5.h>
#include <stdlib.h>
#include <string.h>

char *telId = "0";
char *plat = "squid";
char *sysplat = "speiyou";
char *skey = "com.xes.itempool";
char *uri = "http://icsinterface.speiyou.com/icsinterface/rest/curriculum/queryCacheAndQues";

int md5sum(char *string, int len, unsigned char *digest)
{
    MD5_CTX ctx;

    MD5_Init(&ctx);
    MD5_Update(&ctx, string, len);
    MD5_Final(digest, &ctx);

    return 0;
}

int main(int argc, char *argv[])
{
    int i;
    char buffer[1024] = "";
    unsigned char digest[16];
    CURL *curl;
    CURLcode res;
    struct curl_slist *slist = NULL;

    /* make md5 */
    sprintf(buffer, "%s%s%s%s", telId, plat, sysplat, skey);
    fprintf(stderr, "md5sum('%s')\t", buffer);
    md5sum(buffer, strlen(buffer), digest);
    for (i = 0; i < 16; i++) {
        fprintf(stderr, "%02x", digest[i]);
    }
    fprintf(stderr, "\n");

    /* make url */
    sprintf(buffer, "%s?school=%s", uri, telId);
    fprintf(stderr, "url=%s\n", buffer);

    /* init curl */
    curl = curl_easy_init();
    if (curl == NULL) {
        printf("curl_easy_init() error");
        exit(2);
    }

    /* set url */
    curl_easy_setopt(curl, CURLOPT_URL, buffer);

    /* set http header */
    slist = curl_slist_append(slist, "User-Agent: Cache Squid python");
    slist = curl_slist_append(slist, "Accept: */*");
    slist = curl_slist_append(slist, "Content-type: text/plan");
    sprintf(buffer, "plat: %s", plat);
    slist = curl_slist_append(slist, buffer);
    sprintf(buffer, "sys: %s", sysplat);
    slist = curl_slist_append(slist, buffer);
    sprintf(buffer, "md5: %s", digest);
    slist = curl_slist_append(slist, buffer);
    sprintf(buffer, "key: ");
    slist = curl_slist_append(slist, buffer);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

    /* run the curl */
    res = curl_easy_perform(curl);

    /* clean up */
    curl_slist_free_all(slist);
    curl_easy_cleanup(curl);

    exit(res);
}
